//
//  SLBaseWebViewController.m
//  ShopLeader
//
//  Created by 帅科 on 2020/5/25.
//  Copyright © 2020 ShopLeader. All rights reserved.
//

#import "SLBaseWebViewController.h"
#import "QSNavigationDelegate.h"
#import "SLWKProcessPool.h"

#define QSWebViewPause @"pause" // webview界面不可见
#define QSWebViewResume @"resume" // webview界面重新可见

@interface SLBaseWebViewController ()

@property (nonatomic ,strong) NSDictionary *resumeDict;         // 页面重新可见时前端传参
@property (nonatomic ,strong) QSNavigationDelegate *navigationDelegate; // WKNavigationDelegate
@property (nonatomic ,copy) NSString *statusBarStyleStr;

@end

@implementation SLBaseWebViewController


- (instancetype)init
{
    if (self = [super init]) {
        
        WKWebViewConfiguration *webViewConfiguration = [WKWebViewConfiguration new];
        webViewConfiguration.processPool = [SLWKProcessPool share];
        _webView = [[QSBaseWebView alloc]initWithFrame:CGRectZero configuration:webViewConfiguration];
        
        _navigationDelegate = [[QSNavigationDelegate alloc]initWithWebVC:self];
        _webView.navigationDelegate = _navigationDelegate;
        
    }
    return self;
}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    __XB_WEAK_SELF_YLSLIDE
    _webView.webViewDocumentStateBlock = ^(SLDocumentReadyStateType type) {
        weakSelf.documentReadyState = (int)type;
    };

    [self.view addSubview:_webView];
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(weakSelf.view);
    }];
    if (@available(iOS 11.0, *)) {
        [_webView.scrollView setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    [self sl_setupNotification];
    
    [self.webView loadUrl:self.startPage];
    
    self.statusBarStyleChangeAction = ^(NSString * _Nonnull style, id  _Nonnull param) {
        if (style.length > 0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.statusBarStyleStr = style;
                [weakSelf setNeedsStatusBarAppearanceUpdate];
            });
        }
    };
}

-(UIStatusBarStyle)preferredStatusBarStyle
{
    if ([self.statusBarStyleStr isEqualToString:@"light"]) {
        return UIStatusBarStyleLightContent;
    }else{
        return UIStatusBarStyleDefault;
    }
}


- (void)sl_setupNotification{
    
    __XB_WEAK_SELF_YLSLIDE
    [XBNoticeService.shared observer:self noticeName:UIApplicationDidBecomeActiveNotification block:^(id  _Nullable object, NSDictionary * _Nullable userInfo) {
        
        if (!weakSelf.webView || !weakSelf.isViewLoaded) {return;}
        [weakSelf.webView callHandler:@"appDidBecomeActive" arguments:@[] completionHandler:^(id  _Nullable value) {
        }];
    }];
    
    [XBNoticeService.shared observer:self noticeName:UIApplicationWillResignActiveNotification block:^(id  _Nullable object, NSDictionary * _Nullable userInfo) {

        if (!weakSelf.webView || !weakSelf.isViewLoaded) {return;}
        [weakSelf.webView callHandler:@"appWillResignActive" arguments:@[] completionHandler:^(id  _Nullable value) {
        }];
        
    }];
    
    [XBNoticeService.shared observer:self noticeName:UIApplicationWillEnterForegroundNotification block:^(id  _Nullable object, NSDictionary * _Nullable userInfo) {
        
        if (!weakSelf.webView || !weakSelf.isViewLoaded) {return;}
        [weakSelf.webView callHandler:@"appWillEnterForeground" arguments:@[] completionHandler:^(id  _Nullable value) {
        }];
        
    }];
    
    [XBNoticeService.shared observer:self noticeName:UIApplicationDidEnterBackgroundNotification block:^(id  _Nullable object, NSDictionary * _Nullable userInfo) {
        
        if (!weakSelf.webView || !weakSelf.isViewLoaded) {return;}
        [weakSelf.webView callHandler:@"applicationDidEnterBackground" arguments:@[] completionHandler:^(id  _Nullable value) {
        }];
        
    }];
    
    [XBNoticeService.shared observer:self noticeName:UIKeyboardWillShowNotification block:^(id  _Nullable object, NSDictionary * _Nullable userInfo) {
        [weakSelf.webView hasJavascriptMethod:@"web_onKeyBoardWillShow" methodExistCallback:^(bool exist) {
            if (!exist) { return; }
            [weakSelf.webView callHandler:@"web_onKeyBoardWillShow" arguments:@[@{@"keyBoardinfo": [userInfo mj_JSONObject]}]];
        }];
    }];
    
    [XBNoticeService.shared observer:self noticeName:UIKeyboardWillHideNotification block:^(id  _Nullable object, NSDictionary * _Nullable userInfo) {
        [weakSelf.webView hasJavascriptMethod:@"web_onKeyBoardWillHidden" methodExistCallback:^(bool exist) {
            if (!exist) { return;}
            [weakSelf.webView callHandler:@"web_onKeyBoardWillHidden" arguments:@[@{@"keyBoardInfo": [userInfo mj_JSONObject]}]];
        }];
    }];
}


#pragma mark - view life cycle
- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    // 页面可见回调JS
    __XB_WEAK_SELF_YLSLIDE
    NSDictionary *param = @{@"data":@{},@"resumeParam":self.resumeDict?self.resumeDict:@{}};
    [self.webView callHandler:QSWebViewResume arguments:@[param] completionHandler:^(id  _Nullable value) {
        weakSelf.resumeDict = value;
        NSLog(@"kWebViewresume :%@",value);
    }];
}


- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    // 页面不可见回调jJS
    [self.webView callHandler:QSWebViewPause arguments:@[] completionHandler:^(id  _Nullable value) {
        NSLog(@"kWebViewPause:%@",value);
    }];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}


#pragma mark - WKNavigationDelegate
- (WKNavigationActionPolicy)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction{
    return WKNavigationActionPolicyAllow;
}

- (WKNavigationResponsePolicy)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse{
    return WKNavigationResponsePolicyAllow;
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
}

- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation{
    
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
}

- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{
    [self reloadRequestIfNeeded];
}

#pragma mark - Public Methods


#pragma mark - Private Methods
- (void)reloadRequestIfNeeded {
    if (self.webView.URL != nil) {
        return;
    }
    if (![self isBlankView:self.webView]) {
        return;
    }
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.startPage]
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                         timeoutInterval:20.0];
    [self.webView loadRequest:request];
}

- (BOOL)isBlankView:(UIView *)view {
    Class wkCompositingViewClass = NSClassFromString(@"WKCompositingView");
    if ([view isKindOfClass:[wkCompositingViewClass class]]) {
        return NO;
    }
    for(UIView *subView in view.subviews) {
        if (![self isBlankView:subView]) {
            return NO;
        }
    }
    return YES;
}


#pragma mark - startPage
- (void)setStartPage:(NSString *)startPage{
    _startPage = startPage;
}

- (void)dealloc{
    [XBNoticeService.shared removeObserver:self];
}


@end
